package mmc.server;

import mmc.physics.PhysicsEngine;


public class Engine implements Runnable{
	private Server server;
	private Scene scene;
	private volatile boolean running = true;
	private PhysicsEngine physics;
	
	public Engine(Server server){
		this.server = server;
		scene = this.server.getScene();
		physics = new PhysicsEngine(scene);
		scene.setPhysics(physics);
		new Thread(this).start();
	}

	@Override
	public void run() {
		long now = System.nanoTime(), lastUpdate = now;
		float dt;
		//FPS fps = new FPS();
		
		while(running){
			try{
				now = System.nanoTime();
				dt = (float)((now - lastUpdate)*1e-9);
				//if(scene!=null)
				scene.update(dt);
				lastUpdate = now;
				//fps.notifyRedraw(dt);
				
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {}
			}catch(Exception e){
				e.printStackTrace();
				server.broadcast("Server Error: "+e.getMessage());
				shutdown();
				Server.instance.quit = true;
			}catch(OutOfMemoryError e){
				e.printStackTrace();
				server.broadcast("Server Out of Memory!: "+e.getMessage());
			}
		}
		System.out.println("Shutting down engine...");
		
		scene.shutdown();
	}
	
	public void shutdown(){
		running = false;
	}
}
